package com.yxy.job.system;

import com.yxy.dao.TenantExtendMapper;
import com.yxy.feign.AuthService;
import com.yxy.feign.DTO.TenantListDto;
import com.yxy.feign.VO.TenantExtend2;
import com.yxy.model.TenantExtend;
import com.yxy.utils.PageDataList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 与union auth相关的一些系统定时任务
 *
 * @author yuxiaoyang
 * @date 2020-07-08
 */
@Service
@Slf4j
public class UnionAuthJob {
  @Value("${spring.application.name}")
  private String appName;//从配置文件中读取 项目的appName

  @Autowired
  private AuthService authService;

  @Resource
  private TenantExtendMapper tenantExtendMapper;

  // 从union auth中同步 本app所拥有的tenant
//  @Scheduled(cron = "0/8 * * * * ?") //每8s执行一次
  @Transactional(rollbackFor = Exception.class)
  public void syncTenant() {
    log.info("同步租户任务开始...");
    TenantListDto queryObj = new TenantListDto();
    queryObj.setPageNumber(1);
    queryObj.setPageSize(9999);
    queryObj.setAppName(appName);
    PageDataList<TenantExtend2> tenantExtendPageDataList = authService.getTenantList(queryObj).getContent();
    // 获取到 union auth的 tenant list, 然后同步到本地数据库表 tenant_extend
    List<TenantExtend2> authTenantList = tenantExtendPageDataList.getList();
    for (TenantExtend2 authTenant : authTenantList) {
      long id = authTenant.getId();
      TenantExtend dbObj = tenantExtendMapper.selectByPrimaryKey(id);
      if (dbObj == null) {//无则新增
        TenantExtend insertObj = new TenantExtend();
        BeanUtils.copyProperties(authTenant, insertObj);
        tenantExtendMapper.insertSelective(insertObj);
      } else { //有则修改
        TenantExtend updateObj = new TenantExtend();
        BeanUtils.copyProperties(authTenant, updateObj);
        tenantExtendMapper.updateByPrimaryKeySelective(updateObj);
      }
    }
  }

}
